package com.douyin.video.utils;

import com.app.utils.JsonUtil;
import com.douyin.video.entity.DouyinVideo;
import com.douyin.video.view.DouyinVideoView;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.utils.EmojiStringUtils;
import com.utils.HttpUtil;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: zh
 * @Date: 2018/8/27 09:08
 * @Description:
 */
@Slf4j
@SuppressWarnings("all")
public class DouYinUtil extends HttpUtil {

	public static DouyinVideoView video(String shareUrl) {
		try {
			System.out.println("抖音视频下载");
			String uri = shareUrl;
			uri = getUrl(shareUrl);
			Map<String, String> map = new HashMap<String, String>();
			String json = JsonUtil.formatToStr(map);
			String result = get(uri, map);
			DouyinVideoView view = htmlParser(result);
			return view;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static DouyinVideoView htmlParser(String result) {
		Document doc = Jsoup.parse(result);
		// 获取html的标题
		String title = doc.select("title").text();
		System.out.println(title);
		// 获取视频链接
		String video_url = doc.select("video").attr("src");
		System.out.println(getUrl(video_url));
		video_url = getUrl(video_url);
		// 获取视频链接
		String video_title = doc.select(".user-title").text();
		boolean titleFlag = EmojiStringUtils.hasEmoji(video_title);
		if (titleFlag == true) {
			video_title = EmojiStringUtils.replaceEmoji(video_title);
		}
		System.out.println(video_title);
		// 获取作者名称
		String author_name = doc.select(".user-info-name").text();
		System.out.println(author_name);
		// 获取作者头像
		String author_head_img_url = doc.select(".user-avator").attr("style").replace("background-image:url(", "")
				.replace(")", "");
		System.out.println(author_head_img_url);
		// 获取作者抖音id（暂时获取不到）
		String author_id = doc.select(".user-info-id").text();
		System.out.println(author_id);
		DouyinVideoView view = new DouyinVideoView();
		view.setAuthorHeadImgUrl(author_head_img_url);
		view.setAuthorId(author_id);
		view.setAuthorName(author_name);
		view.setVideoTitle(video_title);
		view.setVideoUrl(video_url);
		return view;
	}

	public static String getUrl(String url) {
		try {
			// System.out.println("访问地址:" + url);
			URL serverUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
			conn.setRequestMethod("GET");
			// 必须设置false，否则会自动redirect到Location的地址
			conn.setInstanceFollowRedirects(false);

			conn.addRequestProperty("Accept-Charset", "UTF-8;");
			conn.addRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
			conn.addRequestProperty("Referer", "http://www.baidu.com/");
			conn.connect();
			String location = conn.getHeaderField("Location");

			serverUrl = new URL(location);
			conn = (HttpURLConnection) serverUrl.openConnection();
			conn.setRequestMethod("GET");

			conn.addRequestProperty("Accept-Charset", "UTF-8;");
			conn.addRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
			conn.addRequestProperty("Referer", "http://zuidaima.com/");
			conn.connect();
			// System.out.println("跳转地址:" + location);
			return location;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 支持国内版本
	 * 
	 * @param url
	 * @return
	 */
	public static DouyinVideo downloadVideo(String url,String dyVideo, HttpServletRequest req, HttpServletResponse res) {
		DouyinVideo view=new DouyinVideo();
		
		try {
			HttpResponse<String> response = Unirest.post(urlProcess(url)).header("cache-control", "no-cache")
					.asString();
			String header = response.getHeaders().toString();
			int startIndexOf = header.lastIndexOf("[");
			int lastIndexOf = header.lastIndexOf("]");
			String decodeUrl = header.substring(startIndexOf + 1, lastIndexOf);
			if (StringUtils.isEmpty(decodeUrl)) {
				log.info("返回链接为空");
				return null;
			} else {
				log.info("去水印成功：" + decodeUrl);
				String watermarkVideo=httpDownload(decodeUrl,dyVideo);
				view.setWatermarkVideo(watermarkVideo);
				view.setWatermarkUrl(decodeUrl);
				return view;
			}
		} catch (Exception e) {
			log.info("错误信息:" + e);
			return null;
		}
	}

	public static String httpDownload(String httpUrl,String dyVideo) {
		// 1.下载网络文件
		int byteRead;
		URL url;
		try {
			url = new URL(httpUrl);
		} catch (MalformedURLException e1) {
//			e1.printStackTrace();
			log.info("获取路径发生错误"+e1);
			return "error";
		}

		try {
			// 2.获取链接
			URLConnection conn = url.openConnection();
			// 3.输入流
			InputStream inStream = conn.getInputStream();

			String file = dyVideo+getRandomString(20) + ".mp4";

			// 3.写入文件
			FileOutputStream fs = new FileOutputStream(file);

			byte[] buffer = new byte[1024];
			while ((byteRead = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteRead);
			}
			inStream.close();
			fs.close();
			return file;
		} catch (IOException e) {
//			e.printStackTrace();
			log.info("发生错误"+e);
			return "error";
		}
	}

	public static String getRandomString(int length) {
		StringBuffer bu = new StringBuffer();
		String[] arr = { "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
				"m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H",
				"I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
		Random random = new Random();
		while (bu.length() < length) {
			String temp = arr[random.nextInt(57)];
			if (bu.indexOf(temp) == -1) {
				bu.append(temp);
			}
		}
		return bu.toString();
	}

	public static String urlProcess(String url2) {
		try {
			String url = decodeHttpUrl(url2);
			Document doc = null;
			try {
				doc = Jsoup.connect(url).timeout(12138).get();
			} catch (Exception e) {
				e.printStackTrace();
			}
			Elements elem = doc.getElementsByTag("script");
			String url1 = elem.toString();
			int start = url1.indexOf("playAddr");
			url1 = url1.substring(start);
			int end = url1.indexOf("\",");
			String processedurl = url1.substring(11, end).replaceAll("playwm", "play");
			return processedurl;
		} catch (Exception e) {
			throw new RuntimeException("错误：" + e);
		}

	}

	public static String decodeHttpUrl(String url) {
		// 检测是否有中文，如果没有中文就是直接地址
		boolean containChinese = isContainChinese(url);
		if (containChinese) {
			int start = url.indexOf("http");
			int end = url.lastIndexOf("/");
			String decodeurl = url.substring(start, end);
			return decodeurl;
		} else
			return url;
	}

	public static boolean isContainChinese(String str) {
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			return true;
		}
		return false;
	}


	/**
	 * 根据路径下载
	 *
	 * @param filePath
	 * @param fileName
	 * @param req
	 * @param res
	 * @throws IOException
	 */
	public static void downloadFile(String filePath, String fileName, HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		String userAgent = req.getHeader("User-Agent");
		if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
			fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		} else {
			// 非IE浏览器的处理：
			fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
		}
		filePath = URLDecoder.decode(filePath, "UTF-8");
		res.setContentType("multipart/form-data");
		res.setCharacterEncoding("UTF-8");
		res.setContentType("video/mpeg4");
		res.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
		filePath=filePath.replaceAll("/","\\");
		FileInputStream fis = new FileInputStream(filePath);
		ServletOutputStream sos = res.getOutputStream();
		int b = 0;
		byte[] buffer = new byte[1024];
		while ((b = fis.read(buffer)) != -1) {
			sos.write(buffer, 0, b);
		}
		fis.close();
		if (sos != null) {
			sos.flush();
			sos.close();
		}
	}
}
